package br.com.amigooo.controller;

import static br.com.caelum.vraptor.view.Results.json;

import java.util.Date;
import java.util.List;


import br.com.amigooo.Session.UserSession;
import br.com.amigooo.model.Item;
import br.com.amigooo.model.Order;
import br.com.amigooo.model.ReturnMessage;
import br.com.amigooo.model.User;
import br.com.amigooo.repository.ItemImpl;
import br.com.amigooo.repository.OrderImpl;
import br.com.amigooo.repository.UserImpl;
import br.com.caelum.vraptor.Consumes;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class OrderController {

	private Result result;
    private UserSession userSession;
    ReturnMessage returnMessage;
	
	public OrderController(Result result, UserSession userSession){
        this.result = result;
        this.userSession = userSession;
	}
	
	@Path("/order/create")
	@Consumes(value="application/json")
	@Post
	public void createOrder(Order order){
		OrderImpl orderImpl = new OrderImpl();
		UserImpl userImpl = new UserImpl();
		ItemImpl itemImpl = new ItemImpl();
		
		User user = null;
		Item item = null;
		
		try{
			if(order != null){
				user = userImpl.getUser(order.getUser().getEmail());
				item = itemImpl.getItem(order.getItem());
				
				order.setEstablishment(order.getEstablishment());
				order.setOpening(new Date());
				order.setUser(user);
				order.setStatus(1);
				order.setQuantity(order.getQuantity());
				order.setItemObj(item);
				Order odr =  orderImpl.save(order);

				this.returnMessage = new ReturnMessage(odr.getId().toString(), null, "Pedido criado");
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("erro", "Ocorreu um erro ao criar o pedido." + e.getMessage(), null);
		}
		
		result.use(json()).from(this.returnMessage).serialize();
	}
	
	@Path("/mobile/listmenu")
	@Get
	public void getMenuList(String type, String establishment) {
		ItemImpl itemImpl = new ItemImpl();
		List<Item> itens = null;

		if(type != null && establishment != null){
			int t = Integer.parseInt(type);
			int c = Integer.parseInt(establishment);
			
			try{
				itens = itemImpl.getItemByCompany(t, c);

				if(itens.size() > 0){
					result.use(json()).from(itens).serialize();
				}else{
					this.returnMessage = new ReturnMessage("7", "error", null);
					result.use(json()).from(this.returnMessage).serialize();
				}
			}catch(RuntimeException e){
				e.printStackTrace();
				this.returnMessage = new ReturnMessage("6", "error", null);
				result.use(json()).from(this.returnMessage).serialize();
			}
		}
	}
}